<script setup lang="ts">
import { reactive, computed, toRef, ref } from "vue";
type Item = {
  id: string;
  name: string;
  price: number;
  num: number;
  isRemoving: boolean;
};
const _defaultData: Item[] = [
  { id: "10001", name: "电瓶车", price: 1300, num: 0, isRemoving: false },
  { id: "10002", name: "手机", price: 5500, num: 0, isRemoving: false },
  { id: "10003", name: "电脑", price: 2999, num: 0, isRemoving: false },
  { id: "10004", name: "服务器", price: 89, num: 0, isRemoving: false },
  { id: "10005", name: "洗洁精", price: 17, num: 0, isRemoving: false },
];
const data = reactive<Item[]>([..._defaultData]);
const keyword = ref("");

const amount = computed(() =>
  data.map((i) => i.price * i.num).reduce((t, v) => t + v, 0)
);

const searchedData = computed(() =>
  data.filter((item) => item.name.includes(keyword.value))
);

const updateNum = (item: Item, num: number) => {
  const i = toRef(item, "num");
  i.value += num;
};

const updateRemoving = (item: Item) => {
  const r = toRef(item, "isRemoving");
  r.value = !r.value;
};

const remove = (item: Item) => {
  data.splice(
    data.findIndex((i) => i.id === item.id),
    1
  );
};

const highlight = (name: string) =>
  name.replace(
    keyword.value,
    `<span style="color:red">${keyword.value}</span>`
  );
</script>

<template>
  <div><input placeholder="输入关键字" v-model="keyword" /></div>
  <table>
    <thead>
      <tr>
        <th>#</th>
        <th style="width: 20%">名称</th>
        <th style="width: 20%">价格</th>
        <th style="width: 20%">数量</th>
        <th style="width: 20%">小计</th>
        <th style="width: 15%">操作</th>
      </tr>
    </thead>
    <tbody>
      <tr v-if="searchedData.length > 0" v-for="item in searchedData">
        <td>{{ item.id }}</td>
        <td v-html="highlight(item.name)"></td>
        <td>￥{{ item.price }}</td>
        <td>
          <button @click="updateNum(item, -1)" :disabled="item.num < 1">
            -
          </button>
          {{ item.num }}
          <button @click="updateNum(item, 1)">+</button>
        </td>
        <td>￥{{ item.price * item.num }}</td>
        <td>
          <button v-if="!item.isRemoving" @click="updateRemoving(item)">
            移除
          </button>
          <div v-else>
            <button @click="remove(item)">确认</button>
            <button @click="updateRemoving(item)">取消</button>
          </div>
        </td>
      </tr>
      <tr v-else>
        <td colspan="6" style="color: red">购物车为空</td>
      </tr>
    </tbody>
  </table>
  <div>合计：￥{{ amount }}</div>
</template>

<style scoped>
* {
  font-size: 0.8rem;
}
table {
  border: none;
  width: 100%;
  border-spacing: 0;
  margin: 1rem auto;
}
th,
td {
  padding: 2px 3px;
  border-bottom: 1px solid #666;
}
</style>
